package com.qxsx.midi.activity.personal;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

/**
 * Created by LYJ on 2015/9/8.
 */
public class PersonalEditPasswordActivity extends BaseActivity implements View.OnClickListener {
    private CustomProgress customProgress;

    private RelativeLayout rl_mess, rl_name, rl_email, rl_position, rl_password, rl_phonenum;
    private LinearLayout ll_back, ll_save;
    private Button bt_send;
    private EditText ed_phone, ed_code, ed_newpass, ed_twopass;
    Intent intent = new Intent();
    // 可以验证
    boolean canChecking = true;
    // 验证用的Timer
    Timer timer;
    // 间隔时间
    final int spacing = 60;
    // 剩余时间
    int lastTime;
    private String verificationCode = "1234";//验证码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_password);
        setTitle("修改密码");
        setNavBtn(R.mipmap.back, null, 0, "保存");
//        ll_back = (LinearLayout)findViewById(R.id.name_back);
//        ll_save = (LinearLayout)findViewById(R.id.name_save);
        ed_phone = (EditText) findViewById(R.id.ed_pass_phone);
        ed_code = (EditText) findViewById(R.id.ed_pass_code);
        ed_newpass = (EditText) findViewById(R.id.ed_pass_newpass);
        ed_twopass = (EditText) findViewById(R.id.ed_pass_twopass);
        bt_send = (Button) findViewById(R.id.bt_pass_send);

//        ll_back.setOnClickListener(this);
//        ll_save.setOnClickListener(this);
        bt_send.setOnClickListener(this);
        String userphone = (String) SPUtils.get(AppContext.getContext(), "user_phone", "");
        ed_phone.setText(userphone);
    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
            case RIGHT:

                String phonenum = ed_phone.getText().toString().trim();
                if (phonenum != null && phonenum != "") {
                    if (!isMobileNO(phonenum)) {
                        showToast("手机号码不正确");
                        return;
                    }
                }
                String code = ed_code.getText().toString().trim();
                if (!code.equals(verificationCode)) {
                    showToast("验证码不正确");
                    return;
                }

                final String newpass = ed_newpass.getText().toString().trim();
                String twopass = ed_twopass.getText().toString().trim();
                if (!newpass.equals(twopass)) {
                    showToast("两次密码必须保持一致");
                    return;
                }
                customProgress = CustomProgress.show(PersonalEditPasswordActivity.this, "正在修改，请稍后....", true, null);
                JSONArray array = new JSONArray();
                JSONObject object = new JSONObject();
                try {
                    object.put("phone", phonenum);
                    object.put("pwd", newpass);
                    array.put(object);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MyNet.doPostJsonArray("108", array, new callBackJsonArray() {
                            @Override
                            public void run(Object code, Object message, JSONArray array) {
                                //  Log.e("-------------", code.toString());
                                if (!code.toString().equals("200")) {
                                    Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                                } else if (array == null) {
                                    Log.w("array", array + "");
                                    return;
                                } else {
                                    Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                                    SPUtils.put(AppContext.getContext(), "login_password", newpass);
                                    finish();

                                }
                                customProgress.dismiss();
                            }
                        }

                );

                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.name_back:
//                //返回
//                intent.setClass(AppContext.getContext(),PersonalDetailsActivity.class);
//                startActivity(intent);
//                finish();
//                break;
            case R.id.bt_pass_send:
                //发送验证码
                String phonenum = ed_phone.getText().toString().trim();
                if (phonenum != null && phonenum != "") {
                    if (!isMobileNO(phonenum)) {
                        showToast("手机号码不正确");
                        return;
                    }
                } else {
                    showToast("手机号码不能为空");
                    return;
                }
                if (canChecking)    // 如果可以获取验证码
                {
                    canChecking = false;
                    timer = new Timer();
                    lastTime = spacing;
                    // bt_send.setBackgroundResource(R.drawable.pub_black_round_gray_bg);
                    final String oldtxt = bt_send.getText().toString();
                    bt_send.setText(lastTime + "s");

                    bt_send.setTextColor(getResources().getColor(R.color.theme_green));
                    //  showToast("验证码1234");
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (lastTime == 0) // 时间到了
                            {
                                PersonalEditPasswordActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // bt_send.setBackgroundResource(R.drawable.pub_white_round_gray_bg);
                                        bt_send.setText(oldtxt);
                                        bt_send.setTextColor(getResources().getColor(R.color.theme_green));
                                        timer.cancel();
                                        timer = null;
                                        canChecking = true;
                                    }
                                });

                            } else {
                                PersonalEditPasswordActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lastTime--;
                                        bt_send.setText(lastTime + "S");
                                    }
                                });

                            }
                        }
                    }, 1000, 1000);
                    final String Code = ed_code.getText().toString().trim();
                    JSONArray array = new JSONArray();
                    JSONObject object = new JSONObject();
                    try {
                        object.put("phone", phonenum);
                        array.put(object);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    MyNet.doPostJsonArray("107", array, new callBackJsonArray() {
                                @Override
                                public void run(Object code, Object message, JSONArray array) {
                                    //  Log.e("-------------", code.toString());
                                    if (!code.toString().equals("200")) {
                                        Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                                    } else if (array == null) {
                                        Log.w("array", array + "");
                                        return;
                                    } else {
                                        try {
                                            JSONObject jsonObject = array.getJSONObject(0);
                                            verificationCode = jsonObject.getString("validate_num");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();

                                    }
                                }
                            }

                    );
                } else            // 不可以获取验证码
                {
                    return;
                }
                break;

        }
    }

    private void showToast(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        return p.matcher(mobiles).matches();
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    // 像素转 dpi
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
